package br.com.affero.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.hibernate.Session;
import org.hibernate.Transaction;

import br.com.affero.util.HibernateUtil;

public class HibernateSessionFilter implements Filter {

	private Session session;
	
    public HibernateSessionFilter() {
    	session = HibernateUtil.getInstance().openSession();
    }

	public void destroy() {		
		session.close();
	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {		
		Transaction tx = session.beginTransaction();
		try {
			chain.doFilter(request, response);
			tx.commit();
		} catch (Exception e) {
			tx.rollback();
			throw e;
		}
	}

	public void init(FilterConfig fConfig) throws ServletException {
	}

}
